import pyglet
from pyglet.graphics import vertex_list_indexed
import math

def seg2D_intersect(A,B,C,D):
    Ax,Ay=A
    Bx,By=B
    Cx,Cy=C
    Dx,Dy=D

    num=(Ay-Cy)*(Dx-Cx)-(Ax-Cx)*(Dy-Cy)
    den=(Bx-Ax)*(Dy-Cy)-(By-Ay)*(Dx-Cx)

    if (den==0):
        print "Parallel !"
        return False
    if num*den<0 :
                return False
    
    from math import fabs
    if math.fabs(num)>math.fabs(den): return False
    
    return True

class Iceberg(object):
    def __init__(self,iName,iPoints):
        self.name=iName

        nP=len(iPoints)
        self.points=iPoints
        self.points3D=[(x*1.0,y*1.0,0.0) for x,y in iPoints]
        
        indices=[]
        for i in range(nP-1):
            indices.extend((i,i+nP,i+1))
            indices.extend((i,i+1,i+nP+1))
        indices.extend((nP-1,2*nP-1,0))
        indices.extend((nP-1,0,nP,0))

        print indices
        pos=[]
        for i in range(nP):
            pos.extend(self.points3D[i])
            
        
        o=(0.0,0.0,0.0)
        
        for p in self.points3D:
            
            pos.extend(self.extrude(o,p,200.))
        
        n=len(pos)
        
        self.vertex_list=pyglet.graphics.vertex_list_indexed(n//3,indices,'v3f',('c3B/static', [128]*n))
        #self.vertex_list=pyglet.graphics.vertex_list(n,'v3f')#,('c3B/static', (128)*n))
        self.vertex_list.vertices=pos
        self.nP=nP

        
        
    def update_shadow(self,origin,distance):
        pos=[]
        for p in self.points3D:
            pos.extend(self.extrude(origin,p,distance))
        self.vertex_list.vertices[self.nP*3:]=pos
    
    def draw(self, origin):
        self.update_shadow(origin,200.)
        self.vertex_list.draw(pyglet.gl.GL_TRIANGLES)
        
    def extrude(self,o,p,d):
        xo,yo,zo=o
        xp,yp,zp=p
        dx=xp-xo
        dy=yp-yo
        d2=dx**2+dy**2
        if d2==0:
            return o
        f=math.sqrt((d**2)/d2)


        x=xo+dx*f
        y=yo+dy*f
        return (x,y,zo)   

    def isBlocking(self,obs,target):
        """ Checks if this iceberg is blocking the view from observer
        to target.
        Takes two tuples with minimum length 2 as arguments
        """
        A=obs[0:2]
        B=target[0:2]
        SegA=self.points[0]
        
        for i in range(1,len(self.points)):
            SegB=self.points[i]
            if seg2D_intersect(A,B,SegA,SegB):
                return True
            SegA=SegB
        return False
 